<template>
    <div class="ntd-container">
        <CommonQueryTool :list-query-params="rule.queryParams" :init-list="initList" :click-add="handleUpdate" />
        <el-table :data="list">
            <el-table-column type="selection" width="55" />
            <el-table-column label="id" prop="id" />
            <template v-for="(item, _index) in rule.tableConfig" :key="_index">
                <el-table-column :label="item.title">
                    <template #default="{ row }">
                        {{ item.type }}
                        <template v-if="isDictCol(item.name)">
                            {{ transformDict(row, item.name) }}
                        </template>
                        <template v-if="item.type === 21">
                            <el-switch v-model="row[item.name]" @change="rowEdit(row)" />
                        </template>
                        <template v-if="item.type === 1">
                            <!-- <span v-copyClipboard="row[item.name]">{{ row[item.name] }}</span> -->
                        </template>
                        <template v-if="item.type === 3">
                            <!-- <span v-dayjs="row[item.name]" /> -->
                        </template>
                        <template v-if="item.type === 42">
                            <span>{{ tags.filter(tag => (row[item.name] || []).includes(tag.id)).map(tag =>
                                    tag.name)
                            }}</span>
                        </template>
                        <template v-if="item.type === 48">
                            <NtdParamsSelect v-model:defaultIds="row[item.name]" @ntdChange="rowEdit(row)" />
                        </template>
                        <template v-if="item.type === 163">
                            <NtdImg :urls="[row[item.name]]"></NtdImg>
                        </template>
                        <template v-if="item.type === 15">
                            <el-popover placement="bottom" :width="200" trigger="click">
                                <el-button type="link" size="small" target="link" :href="record[column.dataIndex]">
                                    跳转
                                </el-button>
                                <el-button v-copyClipboard="record[column.dataIndex]" type="link" size="small"
                                    @click="record.operVisible = false">
                                    复制
                                </el-button>
                                <template #reference>
                                    <el-button>record[column.dataIndex]</el-button>
                                </template>
                            </el-popover>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column :label="item.title" :prop="item.name" />
            </template>
        </el-table>
        <ATable class="table-content" :data-source="list" :columns="columns"
            :pagination="{ pageSize: listQuery.limit, total }" :scroll="{ y: 'calc(70vh)' }" row-key="id" size="small"
            @change="tableChange">
            <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'operation'">
                    <template v-for="rowFun in tableRowFunctions" :key="rowFun.text">
                        <el-button type="link" size="small" @click="handleCustomerClick(record, rowFun)">
                            {{ rowFun.text }}
                        </el-button>
                    </template>
                    <el-button type="link" size="small" @click="handleUpdate(record)">
                        编辑
                    </el-button>
                    <el-button type="link" size="small" @click="handleDelete(record)">
                        删除
                    </el-button>
                </template>
            </template>
        </ATable>
        <AModal :title="dataForm && (dataForm.id ? '编辑' : '创建')" :visible="modalTag" :footer="null" width="80%"
            @cancel="modalTag = false">
            <template v-if="dataForm && modalTag">
                <add-form :form="dataForm" :cancel="() => { modalTag = false }" :init-list="initList" />
            </template>
            <template v-else>
                您的表单数据不合法，请您联系系统管理员进行处理......
            </template>
        </AModal>
        <component :is="componentName" :key="componentName" ref="customerComp" :form="dataForm" />
        <div id="customer-component" class="page-fs"
            style="position: absolute; border: 0px solid red; top: 0; left: 0; z-index: -1" />
        <!--    <el-dialog title="预览" :visible="isPreviewDialog" width="70%">-->
        <!--      <div v-html="previewHtml" />-->
        <!--    </el-dialog>-->
    </div>
</template>

<script setup>
import CommonQueryTool from './component/CommonQuery.vue';
</script>

<script>
// import ToolAxios from '@/tool/ToolAxios';
import ToolElement from '@/tool/ToolElement';
import ContextModel from './context/ContextModel';
import UseTags from '@/components/NtdBlock/ntd-tags-select/UseTags'

let context
export default {
    data() {
        return {
            dataForm: undefined,
            list: undefined,
            total: 50,
            attributes: undefined,
            modalTag: false,
            listQuery: { page: 0, limit: 20 },
            disableFeatures: undefined, // 禁用配置信息
            isPreviewDialog: false, // 预览dialog状态
            previewHtml: '', // 预览内容
            rule: {},
            tableRowFunctions: [],
            componentName: '',
            customerModalTag: true,
            tags: [],
        }
    },
    computed: {
        columns() {
        }
    },
    async mounted() {
        await this.initModel()
        this.initTableRowFun()
        this.initList()
        this.initTags()
    },
    methods: {
        async initTags(ids = []) {
            this.tags = await UseTags(ids).initList();
        },
        async initModel() {
            context = await ContextModel.init(this.$route)
            this.rule = context.rule
            if (this.rule && this.rule.pageConfig) {
                this.listQuery.limit = this.rule.pageConfig.limit || 20
            }
            this.attributes = context.attributes
        },
        initTableRowFun() {
            this.tableRowFunctions = context.rule.tableRowFunctions || []
        },
        rowEdit(row) {
            context.api['edit'](row).then(() => ToolElement.msg())
        },
        transformDict(record, dataIndex) {
            let dictList = this.rule.tableConfig[dataIndex].dictList
            if (!dictList) {
                return record[dataIndex]
            }
            let recordVals = record[dataIndex];
            if (!(recordVals instanceof Array)) {
                recordVals = [recordVals];
            }
            return recordVals.map(recordVal => {
                let dictRes = dictList.filter(dict => dict.val === recordVal)
                if (dictRes.length < 1) {
                    return record[dataIndex]
                }
                return dictRes[0].name
            }).join(',')
        },
        handleCustomerClick(row, tableRowFun) {
            this.componentName = tableRowFun.component
            this.dataForm = { ...row }
            this.$nextTick(() => {
                this.$refs.customerComp.open()
            })
        },
        tableChange(pag, filters, sorter) {
            this.listQuery.page = pag?.current
            this.initList()
        },
        initList(init = false, queryParams = []) {
            if (init === true) {
                this.listQuery.page = 0
            }
            this.listQuery.condition = ToolAxios.condition(queryParams)
            this.list = undefined
            context.api.list(this.listQuery).then(res => {
                this.list = res.records
                this.total = res.totalElements || res.total
                this.initTags();
            })
            this.rule.ruleInit && this.rule.ruleInit()
        },
        handleUpdate(rowData) {
            if (rowData !== undefined) {
                this.dataForm = { ...rowData }
            } else {
                this.dataForm = {}
            }
            this.modalTag = true
        },
        handleDelete(row) {
            context.api.remove(row.id).then(() => {
                ToolElement.msg('删除成功！')
                this.initList(true)
            })
        },
        isDictCol(key) {
            const config = this.rule.tableConfig[key]
            return config && config.dictList && config.dictList.length > 0
        }
    }
}
</script>
<style scoped>
.table-content {
    padding: 0;
}

.ant-table td {
    white-space: nowrap;
}
</style>
